package com.team233.zuccecho.service.impl;

import com.alibaba.fastjson.JSON;
import com.team233.zuccecho.Bean.*;
import com.team233.zuccecho.dto.AnswerDto;
import com.team233.zuccecho.dto.FeedbackDao;
import com.team233.zuccecho.dto.StudentDto;
import com.team233.zuccecho.exception.EchoServiceException;
import com.team233.zuccecho.repository.*;
import com.team233.zuccecho.service.inter.StudentInterface;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@CacheConfig(cacheNames = "student")
@Service
public class StudentImpl implements StudentInterface{
    private final Logger logger = LoggerFactory.getLogger(StudentImpl.class);
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StudentRepository studentRepository;
    @Autowired
    private FeedbackRepository feedbackRepository;
    @Autowired
    private QuestionnaireRepository questionnaireRepository;
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private RestHighLevelClient client;


    @Override
    public long login(long stu_id, String stu_pwd) throws EchoServiceException {
        Student student = studentRepository.findStuById(stu_id);
        if (student == null) throw new EchoServiceException("该学生不存在" + stu_id);
        if (student.getStu_pwd().equals(stu_pwd)) return stu_id;
        return -1;
    }

    @Override
    public Integer modifyPwd(long stu_id, String oldpwd, String newpwd) throws EchoServiceException {
        Student student = studentRepository.findStuById(stu_id);
        if (oldpwd.equals(student.getStu_pwd())) {
            studentRepository.ModifyPwd(newpwd, stu_id);
            return 1;
        }
        throw new EchoServiceException("初始密码错误");
    }

    @Override
    public List<Student> addStu(List<StudentDto> stuList) throws EchoServiceException {
        List<Student> stus = new ArrayList<>();
        for (StudentDto stu : stuList) {
            if (studentRepository.findStuById(stu.getStu_id()) != null)
                throw new EchoServiceException("该学生已存在" + stu.getStu_id());

            Student student = new Student();
            BeanUtils.copyProperties(stu, student);
            System.out.println(student);
            stus.add(student);
        }
        if (stus.size() != 0) {
            studentRepository.saveAll(stus);
            return stus;
        }
        return null;
    }

    @Override
    public List<Feedback> findFeedBack(Long stu_id) throws EchoServiceException {
        Student student=studentRepository.findStuById(stu_id);
        if(student==null)
            throw new EchoServiceException("该学生不存在");

        List<Feedback> feedbackList=student.getFeedbackList();
        if(feedbackList.size()==0)
            return null;
        return feedbackList;
    }

    //学生发布问卷
    @Override
    public Long submitQuestionnaire(FeedbackDao feedbackDao) throws EchoServiceException,IOException {
        Feedback feedback=new Feedback();
        BeanUtils.copyProperties(feedbackDao,feedback);
        Long stu_id=feedbackDao.getStu_id();
        feedback.setStudent(studentRepository.findStuById(stu_id));
        long qn_id=feedbackDao.getQuestionnaire_id();
        feedback.setQuestionnaire(questionnaireRepository.findQNById(qn_id));
        feedback.setFb_time(new Timestamp(System.currentTimeMillis()));
        for(AnswerDto answerDto:feedbackDao.getAnswerDtoList()){
            Answer answer=new Answer();
            BeanUtils.copyProperties(answerDto,answer);
            answer.setFeedback(feedback);
            answer.setQuestion(questionRepository.findQuesById(answerDto.getQuestion_id()));
            feedback.getAnswerList().add(answer);
        }
        feedbackRepository.save(feedback);

        FeedbackEntity feedbackEntity=new FeedbackEntity();
        String answers=feedbackDao.getAnswerDtoList().toString();
        feedbackEntity.setAnswers(answers);
        feedbackEntity.setStu_id(feedbackDao.getStu_id());
        feedbackEntity.setQn_id(feedbackDao.getQuestionnaire_id());
        feedbackEntity.setFb_id(feedback.getFb_id());
//        System.out.print(feedbackEntity);

        //先判断索引是否存在
        GetIndexRequest rq = new GetIndexRequest("feedback");
        boolean exists = client.indices().exists(rq, RequestOptions.DEFAULT);
        //如果索引不存在，则创建索引
        if(!exists){
            CreateIndexRequest request = new CreateIndexRequest("feedback");
            CreateIndexResponse createIndexResponse =
                    client.indices().create(request, RequestOptions.DEFAULT);
            System.out.println(createIndexResponse);
        }

        IndexRequest req=new IndexRequest("feedback");
        req.id(""+feedback.getFb_id());
        req.source(JSON.toJSONString(feedbackEntity), XContentType.JSON);
        IndexResponse indexResponse = client.index(req, RequestOptions.DEFAULT);

        System.out.println(indexResponse.toString());//数据
        System.out.println(indexResponse.status());
        /**
         * 蔡海龙 4/24/2022
         */
        redisTemplate.opsForList().rightPushAll("questionnaire-"+qn_id+":filledNumber",stu_id);
        redisTemplate.opsForList().remove("questionnaire-"+qn_id+":otherNumber",0,stu_id);
        if(redisTemplate.opsForList().range("questionnaire-"+qn_id+":otherNumber",0,-1)==null){
            redisTemplate.delete("questionnaire-"+qn_id+":allNumber");
            redisTemplate.delete("questionnaire-"+qn_id+":filledNumber");
        }

        //在学生提交问卷方法内，更新已填写人数和未填写人数
//        List<Long> otherStuIds=redisTemplate.opsForList().range("questionnaire-"+qn_id+":otherNumber",0,-1);
//        List<Long> saveStuIds;
        //如果没人填写
//        if(redisTemplate.opsForList().range("questionnaire-"+qn_id+":saveNumber",0,-1).size()==0){
//            saveStuIds=new ArrayList<>();
//        }else{
//            saveStuIds=redisTemplate.opsForList().range("questionnaire-"+qn_id+":saveNumber",0,-1);
//        }
//        saveStuIds.add(stu_id);
//        redisTemplate.opsForList().rightPushAll("questionnaire-"+qn_id+":saveNumber",saveStuIds);
//        if(otherStuIds.size()>=1) otherStuIds.remove(stu_id);
//        redisTemplate.opsForList().rightPushAll("questionnaire-"+qn_id+":otherNumber",otherStuIds);
//
//        System.out.println("问卷"+qn_id+"已填写人数："+saveStuIds);
//        System.out.println("问卷"+qn_id+"未填写人数："+otherStuIds);
        return feedback.getFb_id();
    }


    @Override
    public List<String> getQns(long stu_id) throws EchoServiceException {
        List<String> qnInfo = new ArrayList<>();
        List<Questionnaire> questionnaires = questionnaireRepository.getStuALlQn(stu_id);
        if(questionnaires == null){
            qnInfo.add(new String("暂无问卷"));
        }else{
            for (Questionnaire q: questionnaires){
                qnInfo.add(q.toString());
            }
        }
        return qnInfo;
    }

    @Override
    public List<Question> getQn(long qn_id) throws EchoServiceException {
        List<Question> questions= (List<Question>) redisTemplate.opsForValue().get("questionnaire:"+qn_id);
        redisTemplate.opsForValue().set("questionnaire:"+qn_id+"allNumber",questions,1, TimeUnit.HOURS);
        if(questions!=null){
            logger.warn("load paper[{}][{}] from cache.",questions);
            return questions;
        }

        Questionnaire questionnaire = questionnaireRepository.getById(qn_id);
        System.out.println(questionnaire);
        questions = questionnaire.getQuestionSet();

        redisTemplate.opsForValue().set("questionnaire:"+qn_id,questions,1, TimeUnit.HOURS);
        return questions;

        //缓存问卷信息
//        QnAndQuestions qnAndQuestions= (QnAndQuestions) redisTemplate.opsForValue().get("questionnaire:"+qn_id);
//        if(qnAndQuestions!=null){
//            logger.warn("load paper[{}][{}] from cache.",qnAndQuestions);
//            return qnAndQuestions;
//        }
//        Questionnaire questionnaire = questionnaireRepository.getById(qn_id);
//        List<Question> questions = questionRepository.getQnqs(qn_id);
//        QnAndQuestions qnAndQuestions = new QnAndQuestions(questionnaire,questions);
//
//        redisTemplate.opsForValue().set("questionnaire:"+qn_id,qnAndQuestions,1, TimeUnit.HOURS);
//        return qnAndQuestions;
    }

    @Override
    public List<Clazz> QueryStuClazz(long stu_id) throws EchoServiceException {
        Student student=studentRepository.findStuById(stu_id);
        if(student!= null){
            return student.getClazzList();
        }
        throw new EchoServiceException("该学生不存在");
    }

}
